/**
 * 退款单编辑页面
 */

var sysRefundEdit = {};
sysRefundEdit.operation = {};
sysRefundEdit.orderSkuList = null;
sysRefundEdit.orderData = null; // 缓存订单数据

$sysRefundSkuTable = null;
$(function () {
    var sysRefundId = sysRefundEdit.extractId();
    var orderId = sysRefundEdit.extractOrderId();
    sysRefundEdit.sysRefundId = sysRefundId;
    sysRefundEdit.orderId = orderId;

    sysRefundEdit.initComp();
    sysRefundEdit.loadDetail();

    // 从后台加载订单商品列表
    sysRefundEdit.initOrderSkuSelectList();

    // 初始化校验
    $("#sysRefundForm").validate({
        debug: true,
        ignore: "",
        errorPlacement: function (error, element) {
            error.insertAfter(element);
        }
    });
});

//设置输入框和下拉框不可用的title属性
function setInputSelectTitle() {
    var length = $("input").length;
    for (var i = 0; i < length; i++) {
        if ($("input")[i].disabled || $("input")[i].readOnly) {
            $("input")[i].title = $("input")[i].value;
        }
    }
    var sLength = $("select").length;
    for (var i = 0; i < sLength; i++) {
        if ($("select")[i].disabled) {
            var childLength = $("select")[i].children.length;
            for (var j = 0; j < childLength; j++) {
                if ($("select")[i].children[j].value == $("select")[i].value) {
                    $("select")[i].title = $("select")[i].children[j].text;
                    break;
                }
            }

        }
    }
}

// 加载页面明细
sysRefundEdit.loadDetail = function () {
    sysRefundEdit.initDetailTable();
    if (!!sysRefundEdit.sysRefundId) {
        sysRefundEdit.operation.getDetail(sysRefundEdit.sysRefundId);
    } else if (!!sysRefundEdit.orderId) {
        sysRefundEdit.operation.getOrderDetail(sysRefundEdit.orderId);
    }
    setInputSelectTitle();
};

// 初始化页面控件
sysRefundEdit.initComp = function () {
    // 从后台加载退款原因类型列表
    sysRefundEdit.initRefundReasonList();

    // 按钮事件绑定
    $("#orderGoodsAdd").bind("click", function () {
        // 获取表格数据
        var skuCode = $("#orderGoodsSelect").val();
        var skuMark = $("#hidOrderGoodsSelect").val();
        if (!skuCode) {
            window.top.window.showModalAlert("请选择商品");
        } else {
            if (skuMark == "") {
                skuCode = $("#orderGoodsSelect").val();
            } else {
                skuCode = skuCode + "|" + skuMark;
            }
            // 获取已有数据，并校验是否重复
            var existsCode = $sysRefundSkuTable.column(2).data();

            var hasSkuCode = false;

            for (var i = 0, j = existsCode.length; i < j; i++) {
                if (!!existsCode[i] && skuCode.indexOf(existsCode[i]) >= 0) {
                    hasSkuCode = true;
                    break;
                }
            }

            if (existsCode.length > 0 && hasSkuCode) {
                window.top.window.showModalAlert("已存在该规格商品");
            } else {
                var data = sysRefundEdit.orderSkuList[skuCode];
                
                $sysRefundSkuTable.row.add(data).draw();
            }
        }
    });

    // 初始化退款金额控件
    $("#refundFee", $("#sysRefundForm")).inputmask("9{1,8}[.99]", {
        greedy: false,
        placeholder: ''
    });

    $("input[maxlength],textarea[maxlength]", $("#sysRefundForm")).maxlength({
        alwaysShow: false,
        threshold: 40,
        warningClass: "label label-warning",
        limitReachedClass: "label label-danger",
        separator: ' / '
    });
};

sysRefundEdit.initOrderSkuSelectList = function (orderId) {
    $.ajax({
        type: "GET",
        url: "/sysRefundManager/getOrderSkuById.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "orderId": sysRefundEdit.orderId
        },
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                sysRefundEdit.initOrderSkuSelectListWithData(data.data);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

sysRefundEdit.initOrderSkuSelectListWithData = function (data) {
    var orderSkuData = {};

    if (data.length > 0) {
        for (var index in data) {
//        	
            if (data[index].isGift == "n") {
                var deletedLabel = "";
                if(data[index].deleted=="y"){
                    deletedLabel = "[已删除]";
                }
                orderSkuData[data[index].skuCode + "|" + index] = data[index];
                
                $("#orderGoodsList").append(
                    "<option key='"+data[index].orderSkuId+"' deletedStatus='"+data[index].deleted+"' value='" + data[index].skuCode + "|" + index + "' label='" +  deletedLabel+ data[index].goodsName + "|" + data[index].skuName + "|实际支付金额:"
                    + data[index].divideOrderFee + "|购买件数:" + data[index].qty + "'></option>");
            }
        }
    }
    sysRefundEdit.orderSkuList = orderSkuData;

};

function inputSelect(value) {

    var attr = value.split("|");
    value = attr[0];
    var temp = attr[1];
    $("#orderGoodsSelect").val(value);
    $("#hidOrderGoodsSelect").val(temp);
};

sysRefundEdit.validDetail = function () {

    var returnValue = true;
    var rowLength = $sysRefundSkuTable.data().length;
    if (!rowLength) {
        returnValue = false;
        window.top.window.showModalAlert("至少包含1条明细商品");
    }

    var isRefundFeeValid = true;

    $("#sysRefundSkuTable").find("input.refundFee").each(function(index,element){
        if(!$(element).val()||parseFloat($(element).val())==0){
            isRefundFeeValid = false;
            return false;
        }
    });

    if(!isRefundFeeValid){
        returnValue = false;
        window.top.window.showModalAlert("有商品未设置退款金额");
    };
    return returnValue;
};

sysRefundEdit.saveSysRefund = function (context) {

    if ($("#sysRefundForm").valid() && sysRefundEdit.validDetail()) {
        var sysRefundSkuList = $($sysRefundSkuTable.data()).map(function (index, element) {
            var refundFee = $("#sysRefundSkuTable").find(".refundFee").eq(index).val() || 0;
            return {sourceSkuId: this.orderSkuId, refundFee: refundFee}
        }).get();
        
        // 判断退款商品是否已删除且退款单是退货退款
        if("y"===$("#hasGoodReturn").val()){
            for(var i=0,j=sysRefundSkuList.length;i<j;i++){
                var sysRefundObj = sysRefundSkuList[i];
                var selectedOption = $("#orderGoodsList").find("option[key='"+sysRefundObj.sourceSkuId+"']");
                if(selectedOption.attr("deletedStatus")=="y"){
                    // 退款商品包含已删除的订单商品，且是退货退款，则提示
                    window.top.window.showModalAlert("对应商品已删除，不允许退货");
                    return;
                }
            }
        }

        var sysRefundVO = {
            orderCode: $("#orderCode").val(),
            shopName: $("#shopName").val(),
            shopId: $("#shopId").val(),
            refundPhase: $("#refundPhase").val(),
            refundId: $("#refundId").val(),
            refundReason: $("#refundReason").val(),
            ecTradeCode: $("#ecTradeCode").val(),

            consMobile: $("#consMobile").val(),
            refundFee: $("#refundFee").val(),
            refundReasonId: $("#refundReasonId").val(),
            refundReasonName: $("#refundReasonId option:selected").eq(0).text(),
            buyerNick: $("#buyerNick").val(),
            refundType: $("#refundType").val(),

            onOffLine: $("#onOffLine").val(),
            hasGoodReturn: $("#hasGoodReturn").val(),
            buyerRemark: $("#buyerRemark").val(),
            orderId: $("#orderId").val(),
            refundId: $("#refundId").val(),
            refundChannel: $("#refundChannel").val(),
            alipayId: $("#alipayId").val(),
            sysRefundSkuList: sysRefundSkuList
        };
        
        var loading = window.top.window.getIndexBusyOverlay();
        
        $.ajax({
            type: "POST",
            url: "/sysRefundManager/saveSysRefund.action",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(sysRefundVO),
            dataType: "json",
//            async: false,
            beforeSend:function(){
                if(loading) {
                	loading.settext("正在处理中，请稍后...");
                }
            },
            success: function (data) {
                if (data.result == "success") {
                	loading.remove();
                    window.top.window.showScoMessage('ok', data.msg);
                    $('#modalSysRefundDetail', window.top.document).find("#btnClose").click();
                } else {
                    window.top.window.showModalAlert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus) {
            	loading.remove();
                if (XMLHttpRequest.status == 500) {
                    var result = eval("(" + XMLHttpRequest.responseText + ")");
                    window.top.window.showModalAlert(result.errorObject.errorText);
                }
            }
        });
    }
};

// 初始化系统原因类型列表
sysRefundEdit.initRefundReasonList = function () {
    $.ajax({
        type: "GET",
        url: "/rdfundReasonType/getRdfundReasonTypeList.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "start": 0,
            "length": 100,
            "quickSearch": ""
        },
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                initRefundReasonSelector(data.data);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 初始化原因类型
var initRefundReasonSelector = function (refundReasonList) {
    if (refundReasonList.length > 0) {
        $("#refundReasonId").empty();
        $("#refundReasonId").append("<option value=''>请选择</option>");
        for (var index in refundReasonList) {
            $("#refundReasonId").append(
                "<option value='" + refundReasonList[index].refundReasonId + "'>" + refundReasonList[index].refundReasonName + "</option>")
        }
    }
};

// 根据订单ID获取订单明细
sysRefundEdit.operation.getOrderDetail = function (orderId) {
    $.ajax({
        type: "GET",
        url: "/order/getOrderInfo.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "orderId": orderId
        },
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                sysRefundEdit.initAddPage(data.data);
                sysRefundEdit.orderData = data.data;
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 根据退款单ID获取退款单明细
sysRefundEdit.operation.getDetail = function (sysRefundId) {
    $.ajax({
        type: "GET",
        url: "/sysRefundManager/sysRefundDetail.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "sysRefundId": sysRefundId
        },
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                sysRefundEdit.orderId = data.data.orderId;
                sysRefundEdit.operation.getOrderDetail(sysRefundEdit.orderId); // 加载并缓存订单数据
                sysRefundEdit.initEditPage(data.data);
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

// 初始化系统退款单——编辑
sysRefundEdit.initEditPage = function (data) {
    // 根据退款单信息初始化退款单控件取值
    sysRefundEdit.initCompValue4Edit(data);
    // 根据退款单信息初始化退款明细列表
    sysRefundEdit.loadData(data.refundId);
};

sysRefundEdit.loadData = function (refundId) {
    $.ajax({
        type: "GET",
        url: "/sysRefundManager/getOrderSkuByRefundId.action",
        contentType: "application/json;charset=utf-8",
        data: {
            "refundId": refundId
        },
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.result == "success") {
                // 将refundfee转换成input
                for (var i = 0, j = data.data.length; i < j; i++) {
                    data.data[i].refundFee = "<input class='refundFee text-right' type='text' width='100%' value='" + data.data[i].refundFee + "'/>";
                }
                $sysRefundSkuTable.rows.add(data.data).draw();
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                window.top.window.showModalAlert(result.errorObject.errorText);
            }
        }
    });
};

sysRefundEdit.caculateRefundFee = function () {
    var totalValue = 0;
    $("#sysRefundSkuTable").find(".refundFee").each(function () {
        var tempValue = $(this).val();
        if (!!tempValue) {
            totalValue += Number(tempValue);
        }
    });
    $("#refundFee", $("#sysRefundForm")).val(numberParser(totalValue));
};
sysRefundEdit.initDetailTable = function (refundId) {
    // 根据退款ID初始化退款明细列表
    if (null == $sysRefundSkuTable) {
        $sysRefundSkuTable = $("#sysRefundSkuTable").DataTable({
            "processing": true,
            "dom": '<"bottom"rtflp>',
            "searching": false,
            "scrollX": "100%",
            "scrollXInner": "110%",
            "scrollCollapse": false,
            "destroy": true,
            "paging": false,
            "deferRender": true,
            "ordering": false,
            "columns": [{
                "data": "goodsCode",
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "goodsName",
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "skuCode",
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "skuName",
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "ecItemName",
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "ecItemCode",
                "orderable": false,
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "ecSkuCode",
                "orderable": false,
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "ecSkuName",
                "orderable": false,
                "className": "truncate-text tooltip-column-detail"
            }, {
                "data": "qty",
                "className": "text-right truncate-text tooltip-column-detail"
            }, {
                "data": "factUnitPrice",
                "orderable": false,
                "className": "text-right truncate-text tooltip-column-detail",
                "render": numberParser
            }, {
                "className": "text-right truncate-text tooltip-column-detail",
                "data": "actualAmount",
                "orderable": false,
                "render": numberParser
            }
                , {
                    "data": "refundFee",
                    "defaultContent": "<input class='refundFee text-right' type='text' width='100%' value='0'/>",
                    "orderable": false
                }
                , {
                    "className": "text-right truncate-text tooltip-column-detail",
                    "data": "actualPayPrice",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "className": "text-right truncate-text tooltip-column-detail",
                    "data": "divideOrderFee",
                    "orderable": false,
                    "render": numberParser
                }, {
                    "data": "operation",
                    "defaultContent": "<a class='delete-btn' type='button'><i class='fa fa-trash-o'></i></a>",
                }]
        }).on('draw.dt', function () {
            $("#sysRefundSkuTable").find("th.sorting_asc").removeClass("sorting_asc");

            $("#sysRefundSkuTable").tooltip({
                selector: ".tooltip-column-detail",
                container: "body",
                title: function () {
                    if ($(this)[0].scrollWidth > $(this).outerWidth()) {
                        return $(this).text();
                    }
                }
            });
            // 绑定input输入框的inputmask事件和onkeyup事件

            $("#sysRefundSkuTable").find(".refundFee").inputmask("9{1,8}[.99]", {
                greedy: false,
                placeholder: ''
            });

            sysRefundEdit.caculateRefundFee();

            $("#sysRefundSkuTable").find(".refundFee").keyup(function () {
                sysRefundEdit.caculateRefundFee();
            });

            $sysRefundSkuTable.on("click", ".delete-btn", function () {
                var row = $sysRefundSkuTable.row($(this).parents("tr"));
                row.remove();
                $sysRefundSkuTable.draw();
            });
        });

    }
};

sysRefundEdit.initCompValue4Edit = function (refundData) {

    for (var key in refundData) {
        $("input#" + key).val(refundData[key]);
        $("select#" + key).find("option[value='" + refundData[key] + "']").attr("selected", true);
    }
    $("#refundPhase").val(refundData.refundPhase);
    // 设置退款说明为顾客留言
    $("#buyerRemark").text(refundData["buyerRemark"]);
    $("#refundFee").val(numberParser(refundData[refundFee]));
};

sysRefundEdit.initAddPage = function (orderData) {
    for (var key in orderData) {
        $("input#" + key).val(orderData[key]);
        $("select#" + key).find("option[value='" + orderData[key] + "']").attr("selected", true);
    }

    // 设置原单据编号为平台退款单号
    $("#ecTradeCode").val(orderData["tradeCode"]);
    // 设置退款说明为顾客留言
//    $("#buyerRemark").text(orderData["custRemark"]);
};

// 从url中解析系统退款单ID
sysRefundEdit.extractId = function () {
    return extractParam("sysRefundId");
};

// 从url中解析系统订单ID
sysRefundEdit.extractOrderId = function () {

    return extractParam("sysOrderId");
};

// ===========公共方法==========

//获取页面参数
function GetArgsFromHref(sHref, sArgName) {
    var args = sHref.split("?");
    var retval = "";

    if (args[0] == sHref) /*参数为空*/
    {
        return retval;
        /*无需做任何处理*/
    }
    var str = args[1];
    args = str.split("&");
    for (var i = 0; i < args.length; i++) {
        str = args[i];
        var arg = str.split("=");
        if (arg.length <= 1)
            continue;
        if (arg[0] == sArgName)
            retval = arg[1];
    }
    return retval;
}

function extractParam(paramName) {
    var returnString = "";
    var str = window.location.search;
    if (!!str) {
        returnString = GetArgsFromHref(str, paramName);
    }
    return returnString;
}


var numberParser = function (data) {
    var returnValue = "-";
    var numberData = parseFloat(data);
    if (numberData === +numberData) {
        returnValue = numberData.toFixed(2);
    }
    return returnValue;
}